package xyz.xiaomeiqiu.netty.inbound;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.xiaomeiqiu.netty.filter.HeaderHttpRequestFilter;
import xyz.xiaomeiqiu.netty.filter.HttpRequestFilter;
import xyz.xiaomeiqiu.netty.outbound.HttpOutboundHandler;

import java.util.List;

public class HttpInboundHandler extends ChannelInboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(getClass());
//    private final List<String> proxyServer;
    private final HttpOutboundHandler handler;

    private final HttpRequestFilter filter = new HeaderHttpRequestFilter();

    public HttpInboundHandler(List<String> proxyServer){
        logger.info("HttpInboundHandler 初始化");
//        this.proxyServer = proxyServer;
        this.handler = new HttpOutboundHandler(proxyServer);
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            FullHttpRequest httpRequest = (FullHttpRequest) msg;
            handler.handle(httpRequest, ctx, filter);
        } catch (Exception e){
            logger.error("inbound 发生异常", e);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
//
//    private void handlerRequest(FullHttpRequest httpRequest, ChannelHandlerContext ctx, String responseMsg, CharSequence contentType) {
//        FullHttpResponse httpResponse = null;
//        try {
//            byte[] bytes = responseMsg.getBytes("UTF-8");
//            httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(bytes));
//            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType==null?HttpHeaderValues.APPLICATION_JSON:contentType);
//            httpResponse.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, bytes.length);
//
//        } catch (Exception e) {
//            Logger.error("处理http response 发生错误", e);
//            httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT);
//        } finally {
//            if(httpResponse != null){
//                if(!HttpUtil.isKeepAlive(httpRequest)){
//                    ctx.write(httpResponse).addListener(ChannelFutureListener.CLOSE);
//                } else {
//                    httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
//                    ctx.write(httpResponse);
//                }
//            }
//        }
//    }
}
